package cn.trda.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

public class ValidationCodeUtil {
	
	public static String getCode(HttpServletResponse response) throws IOException {
		int width = 120;
		int height = 25;
		// 创建一副内存图像：BufferedImage
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 得到属于该图片的画笔：Graphics
		Graphics g = image.getGraphics();
		// 画边框
		g.setColor(Color.BLUE);
		g.drawRect(0, 0, width, height);
		// 填充背景色
		g.setColor(Color.white);
		g.fillRect(1, 1, width - 2, height - 2);
		// 画干扰线
		g.setColor(Color.GRAY);

		Random r = new Random();
		for (int i = 0; i < 10; i++)
			g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));

		// 随机字母
		
		g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 20));
		int x = 23;
		String [] words=new String[]{"a","b","c","d","e","1","2","3","4","5","6","7","8","9","0","f","g","h","j"};
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < 4; i++) {
			//每个字设置着色
			g.setColor(new Color(r.nextInt(250)+1));
			int a=r.nextInt(words.length);
			sb.append(words[a]);
			//间隔20像素依次写随机位置的字符
			g.drawString(words[a], x, 20);
			//间隔20像素
			x += 20;
		}
		//System.out.println("生成的验证码是==============>"+sb.toString());
		// 将图片写入到页面上
		ImageIO.write(image, "jpg", response.getOutputStream());
		return sb.toString();

	}

	
}
